import 'package:get/get.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/utils/index.dart';
import 'index.dart';
import 'org_person_list/index.dart';

class ContactController extends GetxController {
  ContactController();

  final state = ContactState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    loadContact();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  void loadContact() async {
    if (O2ContactPermissionManager.instance.isCurrentPersonCannotQueryAll()) {
      OLogger.i('当前用户没有权限查询通讯录');
      return ;
    }
    var dn = O2ApiManager.instance.o2User?.distinguishedName;
    if (dn != null && dn.isNotEmpty) {
      var myIdentities =
          await OrganizationControlService.to.identityListByPerson(dn);
      if (myIdentities != null && myIdentities.isNotEmpty) {
        loadMyDepartments(myIdentities);
        if (!O2ContactPermissionManager.instance.isCurrentPersonCannotQueryOuter()) {
           loadTopUnit(myIdentities);
        } else {
          OLogger.i('当前用户没有权限查询外部门！');
        }
      }
    }
  }

  void loadMyDepartments(List<O2Identity> identities) async {
    var myDepartments = await OrganizationAssembleExpressService.to
        .unitListWithIdentities(
            identities.map((e) => e.distinguishedName!).toList());
    if (myDepartments != null && myDepartments.isNotEmpty) {
      // 查询排除
      List<O2Unit> newList = [];
      for (var element in myDepartments) {
        if (!O2ContactPermissionManager.instance.isExcludeUnit(element.distinguishedName??'')) {
          newList.add(element);
        }
      }
      state.myDepartments.addAll(newList);
    }
  }

  void loadTopUnit(List<O2Identity> identities) async {
    state.topUnit.clear();
    List<O2Unit> tops = [];
    // var major = identities.firstWhereOrNull((element) => element.major == true);
    // major ??= identities[0];
    // 改成全部顶级列示
    for (var i = 0; i < identities.length; i++) {
      final idDn = identities[i].distinguishedName;
      if (idDn?.isEmpty == true) {
        continue;
      }
      var unitTop = await OrganizationAssembleExpressService.to.unitByIdAndLevel(idDn!, 1);
      if (unitTop != null) {
        if (!O2ContactPermissionManager.instance.isExcludeUnit(unitTop.distinguishedName??'')) {
          if (!tops.any((uniqueObj) => uniqueObj.distinguishedName == unitTop.distinguishedName)) { // 去重复
            tops.add(unitTop);
          }
        }
      }
    }
    state.topUnit.addAll(tops);
  }

  void openSearchContact() {
    if (O2ContactPermissionManager.instance.isCurrentPersonCannotQueryAll() || O2ContactPermissionManager.instance.isCurrentPersonCannotQueryOuter()) {
      OLogger.i('当前用户没有权限搜索通讯录');
      Loading.toast('contact_no_permission'.tr);
      return ;
    }
    Get.toNamed(O2OARoutes.homeContactSearch);
  }
  void openDept(O2Unit o2unit) {
    OrgPersonListPage.open(top: o2unit);
  }
}
